﻿using System;
using System.ComponentModel;
using System.Diagnostics;
using System.ServiceProcess;

namespace CommandRunner.Service
{
    public partial class CommandRunnerService : ServiceBase
    {
        private Server.Server _server;
        private bool _run;

        public CommandRunnerService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            _server = new Server.Server();

            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(StartServer);
            worker.RunWorkerAsync();
        }

        private void StartServer(object sender, DoWorkEventArgs e)
        {
            _run = true;
            while (_run)
            {
                try
                {
                    _server.Start();
                }
                catch (Exception exception)
                {
                    EventLog eventLog = this.EventLog;
                    eventLog.WriteEntry(string.Format("{0}{1}{2}", exception.Message, System.Environment.NewLine, exception.StackTrace), EventLogEntryType.Error);
                }
            }
        }

        protected override void OnStop()
        {
            _run = false;
            _server.Stop();
        }
    }
}
